package org.geektimes.web.mvc.header;

import org.geektimes.web.mvc.header.matedata.ParamInfo;
import org.geektimes.web.mvc.header.matedata.WebContent;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* 抽象的参数解析器  
* @author : KangNing Hu
*/
public abstract class AbstractParamParse implements ParamParse {

	@Override
	public Object parse(WebContent webContent, ParamInfo paramInfo) {
		ServletRequest servletRequest= webContent.getRequest();
		ServletResponse servletResponse = webContent.getResponse();
		if (!(servletRequest instanceof HttpServletRequest) || !(servletResponse instanceof HttpServletResponse)){
			throw new IllegalStateException("暂不支持非http/https以为的协议");
		}
		return parse0(webContent , paramInfo);
	}


	/**
	 * 转换为http
	 * @param servletRequest servlet请求对象
	 * @return
	 */
	protected HttpServletRequest toHttp(ServletRequest servletRequest){
		return (HttpServletRequest) servletRequest;
	}


	/**
	 * 转换为http
	 * @param servletResponse servlet响应对象
	 * @return
	 */
	protected HttpServletResponse toHttp(ServletResponse servletResponse){
		return (HttpServletResponse) servletResponse;
	}



	protected abstract Object parse0(WebContent webContent, ParamInfo paramInfo );

	/**
	 * 类型转换
	 * @param value 待转换值
	 * @param type  转换最终类型
	 * @return 转换后的值
	 */
	public Object transType(String value , Class type){
		if (value == null){
			return null;
		}
		Object result = null;
		///TODO 暂时只支持常用8大类型 及其 string
		if (type == String.class){
			result = value;
		}else if (type == Integer.class || type == int.class){
			result = Integer.valueOf(value);
		}else if (type == Long.class || type == long.class){
			result = Long.valueOf(value);
		}else if (type == Short.class || type == short.class){
			result = Short.valueOf(value);
		}else if (type == Byte.class || type == byte.class){
			result = Byte.valueOf(value);
		}else if (type == Float.class || type == float.class){
			result = Float.valueOf(value);
		}else if (type == Double.class || type == double.class){
			result = Double.valueOf(value);
		}else if (type == Character.class|| type == char.class){
			result = value.toCharArray()[0];
		}else if (type == Boolean.class || type  == boolean.class){
			result = Boolean.valueOf(value);
		}else {
			throw new IllegalArgumentException("不支持的类型" + type.getName());
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println(int.class == Integer.class);
	}
}
